package foo.proj.action;

import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import foo.base.BaseAction;
import foo.proj.bo.ProjBO;
import foo.proj.vo.ProjMaintainForm;
import foo.proj.vo.ProjQueryForm;
import foo.proj.vo.ProjVvo;
import foo.proj.vo.WbsVvo;
import foo.websystem.action.Consts;
import foo.websystem.bo.SystemBO;

@Controller
@RequestMapping("/proj")
public class ProjAction extends BaseAction {
	private final static String LIST_PROJ_PAGE = "/proj/po-r";
	private final static String MAINTAIN_PROJ_PAGE = "/proj/po-c";
	@Autowired
	protected ProjBO projBO;
	private static final String PROJ_EDITED = "projEdited";// 設定前端頁面是否可以編輯(的參數Key值)
	private static final String WBS_TYPES = "wbsTypes";
	@Autowired
	private SystemBO systemBO;

	@RequestMapping("/initQueryProj")
	public ModelAndView initQueryProj(
			@ModelAttribute("command") ProjQueryForm command,
			HttpSession session) {
		logger.debug("執行 init project");
		ModelAndView mav = new ModelAndView(LIST_PROJ_PAGE);
		try {
			Map<String, String> dropDown = projBO.findProjDropDown(systemBO
					.getUser(session).getUserId());
			session.setAttribute("searchProjs", dropDown);
			session.setAttribute(PROJ_EDITED, Boolean.FALSE);
		} catch (Exception e) {
			logger.error(ExceptionUtils.getStackTrace(e));
			mav.addObject(Consts.MSG, "頁面初始化失敗:" + e.getMessage());
		}
		return mav;
	}

	@RequestMapping("/findProj")
	public ModelAndView findProj(
			@ModelAttribute("command") ProjQueryForm command) {
		logger.debug("findProj輸入參數:" + command.getSearchProj());
		ModelAndView mav = new ModelAndView(LIST_PROJ_PAGE);// 導回原頁
		try {
			List<ProjVvo> dataSet = projBO.findProjs(command.getSearchProj());
			mav.addObject("dataSet", dataSet);
		} catch (Exception e) {
			logger.error(ExceptionUtils.getStackTrace(e));
			mav.addObject(Consts.MSG, "查詢失敗:" + e.getMessage());
		}
		return mav;

	}

	@RequestMapping("/initAddProj")
	public ModelAndView initAddProj(HttpSession session,
			@ModelAttribute("projMaintainForm") ProjMaintainForm form) {
		logger.debug("初始化新增Proj");
		ModelAndView mav = new ModelAndView(MAINTAIN_PROJ_PAGE);
		try {
			session.setAttribute(PROJ_EDITED, Boolean.FALSE);
			Map<String, String> dropDown = projBO.findWbsTypeDropDown();
			session.setAttribute(WBS_TYPES, dropDown);
		} catch (Exception e) {
			logger.error(ExceptionUtils.getStackTrace(e));
			mav.addObject(Consts.MSG, "頁面初始化失敗:" + e.getMessage());
		}
		return mav;
	}

	// 測試 @PathVariable的使用, 無意義
	@RequestMapping(value = "/{sn}/initEditProj", method = RequestMethod.GET)
	public String initEditProj(
			@PathVariable("sn") String sn,
			Model model,
			HttpSession session,
			@ModelAttribute("projMaintainForm") ProjMaintainForm projMaintainForm) {
		logger.debug("初始化編輯Proj: SN:" + sn);
		try {
			session.setAttribute(PROJ_EDITED, Boolean.FALSE);
			Map<String, String> dropDown = projBO.findWbsTypeDropDown();
			session.setAttribute(WBS_TYPES, dropDown);
			loadProjFromDbToForm(model, projMaintainForm, sn);

		} catch (Exception e) {
			logger.error(ExceptionUtils.getStackTrace(e));
			model.addAttribute(Consts.MSG, "取得專案資訊失敗:" + e.toString());
		}

		return MAINTAIN_PROJ_PAGE;
	}

	private void loadProjFromDbToForm(Model model,
			ProjMaintainForm projMaintainForm, String sn) {
		ProjVvo vo = projBO.findProjsByPk(sn);
		projMaintainForm.setProjSn(vo.getSn());
		projMaintainForm.setProjName(vo.getName());
		projMaintainForm.setProjDscr(vo.getContent());
		List<WbsVvo> wbss = projBO.findWbsByProj(sn);
		model.addAttribute(wbss);
	}

	@RequestMapping(value = "/editProj", params = "edit")
	public String editProj(ProjMaintainForm projMaintainForm,
			HttpSession session) {
		logger.debug("/editProj?edit");
		session.setAttribute(PROJ_EDITED, Boolean.TRUE);
		return MAINTAIN_PROJ_PAGE;
	}

	@RequestMapping(value = "/editProj", params = "cancel")
	public String cancelProj(
			HttpServletRequest request,
			Model mav,
			@ModelAttribute("projMaintainForm") ProjMaintainForm projMaintainForm,
			HttpSession session) {
		logger.debug("/editProj?cancle");
		logger.debug(request.getParameterMap());
		session.setAttribute(PROJ_EDITED, Boolean.FALSE);
		try {
			loadProjFromDbToForm(mav, projMaintainForm,
					projMaintainForm.getProjSn());
		} catch (Exception e) {
			logger.error(ExceptionUtils.getStackTrace(e));
			mav.addAttribute(Consts.MSG, "取消失敗??:" + e.getMessage());
		}
		return MAINTAIN_PROJ_PAGE;
	}

	@RequestMapping("/saveProj")
	public String saveProj(
			HttpSession session,
			Model model,
			@ModelAttribute("projMaintainForm") ProjMaintainForm projMaintainForm) {
		logger.debug("執行saveProj");
		try {
			String sn = projBO.saveOrUpdateProj(projMaintainForm.getProjSn(),
					projMaintainForm.getProjName(),
					projMaintainForm.getProjDscr());
			projMaintainForm.setProjSn(sn);
			model.addAttribute("projSn", sn);
			session.setAttribute(PROJ_EDITED, Boolean.FALSE);
			model.addAttribute(Consts.MSG, "儲存成功");
		} catch (Exception e) {
			logger.error(ExceptionUtils.getStackTrace(e));
			model.addAttribute(Consts.MSG, "儲存失敗:" + e.getMessage());
		}
		return MAINTAIN_PROJ_PAGE;
	}

	@RequestMapping("/initEditWbs")
	public @ResponseBody
	WbsVvo initEditWbs(@RequestParam("sn") String wbsSn) {
		WbsVvo vo = projBO.findWbsByPk(wbsSn);
		logger.debug("VO:" + vo);
		return vo;
	}

	@RequestMapping("/findWbs")
	public ModelAndView findWbs(
			@ModelAttribute("projMaintainForm") ProjMaintainForm projMaintainForm) {
		ModelAndView mav = new ModelAndView(MAINTAIN_PROJ_PAGE);
		List<WbsVvo> wbsvos = projBO.findWbs(
				projMaintainForm.getSearchWbsName(),
				projMaintainForm.getSearchWbsTypeId(),
				projMaintainForm.getProjSn());
		mav.addObject(wbsvos);
		return mav;
	}

	@RequestMapping("/addWbs")
	public String addWbs(
			HttpSession session,
			Model mav,
			@ModelAttribute("projMaintainForm") ProjMaintainForm projMaintainForm) {
		logger.debug("執行addWbs");
		try {
			boolean isValidate = true;// 系統性檢核
			StringBuilder errMsg = new StringBuilder();
			String projSn = projMaintainForm.getProjSn();
			if (StringUtils.isBlank(projSn)) {
				errMsg.append("/先儲存專案資料");
				isValidate = false;
			}
			if (!isValidate) {
				if (errMsg.length() > 0) {
					mav.addAttribute(Consts.MSG, errMsg.deleteCharAt(0)
							.toString());
				}
				return MAINTAIN_PROJ_PAGE;
			}
			String wbsName = projMaintainForm.getEditWbsName();
			String estHr = projMaintainForm.getEditEstHr();
			String typeId = projMaintainForm.getEditWbsTypeId();
			logger.debug("輸入參數:" + wbsName + "/" + estHr + "/" + typeId);
			projMaintainForm.setEditEstHr(null);
			projMaintainForm.setEditWbsName(null);
			projMaintainForm.setEditWbsTypeId(null);
			projBO.insertWbs(projSn, wbsName, estHr, typeId);
			loadProjFromDbToForm(mav, projMaintainForm, projSn);
			mav.addAttribute(Consts.MSG, "新增完成");
		} catch (Exception e) {
			logger.error(ExceptionUtils.getStackTrace(e));
			mav.addAttribute(Consts.MSG, "系統錯誤:" + e.getMessage());
		}
		return MAINTAIN_PROJ_PAGE;

	}

	@RequestMapping("/modifyWbs")
	public String modifyWbs(
			@ModelAttribute("projMaintainForm") ProjMaintainForm projMaintainForm,
			Model mav) {
		try {
			projBO.udpateWbs(projMaintainForm.getEditWbsSn(),
					projMaintainForm.getEditWbsName(),
					projMaintainForm.getEditWbsTypeId(),
					projMaintainForm.getEditEstHr());
			loadProjFromDbToForm(mav, projMaintainForm,
					projMaintainForm.getProjSn());
			mav.addAttribute(Consts.MSG, "儲存完成");
		} catch (Exception e) {
			logger.error(ExceptionUtils.getStackTrace(e));
			mav.addAttribute(Consts.MSG, "系統錯誤:" + e.getMessage());
		}
		return MAINTAIN_PROJ_PAGE;
	}

	@RequestMapping(value = "/deleteWbs")
	public String deleteWbs(
			Model mav,
			@ModelAttribute("projMaintainForm") ProjMaintainForm projMaintainForm) {
		try {
			projBO.deleteWbs(projMaintainForm.getEditWbsSn());
			loadProjFromDbToForm(mav, projMaintainForm,
					projMaintainForm.getProjSn());
			mav.addAttribute(Consts.MSG, "刪除完成");
		} catch (Exception e) {
			logger.error(ExceptionUtils.getStackTrace(e));
			mav.addAttribute(Consts.MSG, "系統錯誤:" + e.getMessage());
		}
		return MAINTAIN_PROJ_PAGE;
	}
}
